package top.zerozoo.learn.grade.servlet;

import org.apache.commons.beanutils.BeanUtils;
import top.zerozoo.learn.grade.entity.CourseScore;
import top.zerozoo.learn.grade.factory.ServiceFactory;
import top.zerozoo.learn.grade.service.CourseScoreService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/scoreAdd.do")
public class ScoreAddServlet extends HttpServlet {
    private final CourseScoreService courseScoreService = ServiceFactory.get(CourseScoreService.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (parameterMap.size() < 3) {
            req.getRequestDispatcher("/scoreAdd.jsp").forward(req, resp);
            return;
        }
        CourseScore courseScore = new CourseScore();
        try {
            BeanUtils.populate(courseScore, parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        courseScoreService.insert(courseScore);

        resp.sendRedirect(req.getContextPath() + "/studentDetail.do?id=" + courseScore.getStudentID());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
